﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace WebsiteUI.Extensions
{
    public class CryptoAes
    {
        private static readonly byte[] key = { 0xd6, 0x43, 0xd7, 0x89, 0xd3, 0xe4, 0xb4, 0xea, 0x4e, 0xc2, 0xbd, 0x5e, 0x52, 0xc4, 0x2c, 0xb1, 0x15, 0x89, 0xd4, 0xaa, 0x5f, 0xfb, 0x4f, 0xc6, 0x3c, 0xd8, 0xe5, 0x7e, 0xcb, 0x6f, 0x40, 0x67 };
        private static readonly byte[] iv = { 0x4e, 0xc2, 0xbd, 0x7e, 0x52, 0xc7, 0x2c, 0xb2, 0xd0, 0x30, 0x7e, 0x1e, 0xd1, 0x20, 0x76, 0x6b };

        public static string AESDecrypto(string code)
        {
            try
            {
                byte[] cipherText = Convert.FromBase64String(code);
                SymmetricAlgorithm alg = Rijndael.Create();
                alg.Key = key;
                alg.IV = iv;
                byte[] decryptBytes = new byte[cipherText.Length];
                var ms = new MemoryStream(cipherText);
                var cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Read);
                cs.Read(decryptBytes, 0, decryptBytes.Length);
                cs.Close();
                ms.Close();
                string result = Encoding.UTF8.GetString(decryptBytes);
                result = result.Remove(result.IndexOf('\0'));
                return result;
            }
            catch
            {
                throw new Exception("参数不正确，请重新检查！");
            }
        }

        /// <summary>
        /// AES加密方法！
        /// </summary>
        /// <param name="cipherText"></param>
        /// <returns></returns>
        public static string AESEncrypto(string text)
        {
            SymmetricAlgorithm alg = Rijndael.Create();
            alg.Mode = CipherMode.CBC;
            alg.Padding = PaddingMode.PKCS7;
            alg.Key = key;
            alg.IV = iv;
            ICryptoTransform transform = alg.CreateEncryptor();
            byte[] plainText = Encoding.UTF8.GetBytes(text);
            byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);
            return Convert.ToBase64String(cipherBytes);
        }
    }
}